package org.bt.auth.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SmUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bt.auth.entity.User;
import org.bt.auth.exception.AuthServerException;
import org.bt.auth.mapper.UserMapper;
import org.bt.auth.vo.UserVo;
import org.bt.common.convertor.Convertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.Optional;

/**
 * @author zwj
 * @date 2022/8/17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> {

    @Autowired
    private Convertor<UserVo, User> convertor;

    /**
     * Base64编码
     */
    private static final java.util.Base64.Encoder ENCODER = java.util.Base64.getEncoder();

    /**
     * Base64解码
     */
    private static final java.util.Base64.Decoder DECODER = java.util.Base64.getDecoder();

    public void add(User user) {
        if (Optional.ofNullable(baseMapper.getUserByUsername(user.getUsername())).isPresent()) {
            throw new AuthServerException("账号已存在");
        }
        byte[] salt = getSalt();
        user.setSalt(ENCODER.encodeToString(salt));
        user.setPassword(ENCODER.encodeToString(SmUtil.sm3WithSalt(salt).digest(user.getPassword())));
        this.save(user);
    }

    public void update(UserVo userVo) {
        if (!userVo.getId().equals(StpUtil.getExtra("id"))) {
            throw new AuthServerException("请确认是否为当前账号");
        }
        User user = new User();
        convertor.convert(userVo, user);
        this.updateById(user);
    }


    public static byte[] getSalt() {
        /*
         * 随机生成128位的随机数
         */
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[16];
        random.nextBytes(bytes);
        return bytes;
    }
}
